package com.ww7h.ui.base.ui.adapter

import android.graphics.Canvas
import android.graphics.Rect
import android.util.SparseArray
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.ww7h.ui.base.ui.adapter.item.ItemSpace

/**
 * ================================================
 * 描述：
 * 来源：     Android Studio.
 * 项目名：   BigObj
 * 包名：     com.ww7h.ui.base.ui.adapter
 * 创建时间：  2020/11/10 01:04
 * @author   ww
 * ================================================
 */
class RecyclerItemDecoration(private var spaceArray: SparseArray<ItemSpace>): RecyclerView.ItemDecoration() {

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        val left = parent.left
        val right = parent.right
        val childCount = parent.childCount

        // 遍历所有展示的 itemView 为其添加上下填充视图
        for (i in 0 until childCount) {
            val view = parent.getChildAt(i)
            val viewHolder = parent.getChildViewHolder(view)
            val itemSpace = spaceArray[viewHolder.itemViewType]

            // 绘制上间隔填充物
            itemSpace?.topDrawable?.setBounds(
                left + itemSpace.topDrawableMargin.left + itemSpace.rect.left,
                (view.y - itemSpace.rect.top).toInt() + itemSpace.topDrawableMargin.top,
                right - itemSpace.topDrawableMargin.right - itemSpace.rect.right,
                view.y.toInt() - itemSpace.topDrawableMargin.bottom
            )
            itemSpace?.topDrawable?.draw(c)
            // 绘制下间隔填充物
            itemSpace?.bottomDrawable?.setBounds(
                left + itemSpace.bottomDrawableMargin.left  + itemSpace.rect.left,
                (view.y + view.height).toInt() + itemSpace.bottomDrawableMargin.top,
                right - itemSpace.bottomDrawableMargin.right - itemSpace.rect.right,
                (view.y + view.height).toInt() + itemSpace.rect.bottom - itemSpace.bottomDrawableMargin.bottom
            )
            itemSpace?.bottomDrawable?.draw(c)
        }

    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        val viewHolder = parent.getChildViewHolder(view)
        val itemSpace = spaceArray[viewHolder.itemViewType]
        itemSpace?.rect?.apply {
            outRect.top = top
            outRect.bottom = bottom
            outRect.left = left
            outRect.right = right
        }
    }

}